using System;
using System.IO;
using System.Text;
using BearUtil;
using Sirenix.OdinInspector;
using UnityEditor;
using UnityEngine;


/// <summary>
/// 动态节点
/// </summary>
[Serializable, InlineEditor]
public class DynamicDialogue : DynamicProp
{
    /// <summary>
    ///  生成
    /// </summary>
    [Button("生成", ButtonSizes.Large), GUIColor(0.7f, 0.6f, 0.7f)]
    public override void Generate()
    {
        if (props == null || props.Count <= 0 || string.IsNullOrEmpty(nodeName) || checkSameName())
            return;
        
        Debug.Log("生成 节点脚本");
        ZHName = !string.IsNullOrEmpty(ZHName) ? ZHName : nodeName;
        var filePath = NodeMethodUtil.Delete(CreateNewDialog.Instance.GeneratePath, nodeName + ".cs");
        using (var sw = new StreamWriter (File.Open(filePath, FileMode.CreateNew), Encoding.UTF8))
        {        
            var scriptTxt = new StringBuilder("using XNode;\n");
            scriptTxt.Append("using System.Collections.Generic;\n");
            scriptTxt.Append("using Sirenix.OdinInspector;\n");
            scriptTxt.Append("using BearUtil.Hidden;\n");
            scriptTxt.Append("using UnityEngine;\n");

            scriptTxt.Append("namespace BearUtil\n");
            scriptTxt.Append("{\n");
            if (NodeColor == Color.white)
                scriptTxt.Append($"\t[CreateNodeMenu(\"剧情节点/{ZHName}\"), Title(\"{ZHName}\")]\n");
            else
                scriptTxt.Append($"\t[CreateNodeMenu(\"剧情节点/{ZHName}\"), Title(\"{ZHName}\"), NodeTintAttribute(\"#{ColorUtility.ToHtmlStringRGB(NodeColor)}\")]\n");
            scriptTxt.Append($"\tpublic class {nodeName} : BearDialog\n");
            scriptTxt.Append("\t{\n");

            // fill node property
            for (int i = 0; i < props.Count; i++)
            {
                var prop = props[i];

                scriptTxt.Append(DynamicNodeHelper.AssignProp(prop));
            }

            scriptTxt.Append("\t}\n");
            scriptTxt.Append("}\n");

            sw.Write(scriptTxt.ToString());
            sw.Close();
        }
        
        AssetDatabase.Refresh();
        CreateNewDialog.Instance.UpdateFormat();
    }
}